<template>
  <el-select
    placeholder="请选择"
    v-model="selectValue"
    :disabled="disabled"
    filterable
    collapse-tags
    collapse-tags-tooltip
    :clearable="clearable"
    :filter-method="handleQuerySearch"
    @change="handleQueryChange"
    :multiple="multiple"
    @visible-change="visibleList"
  >
    <el-option
      v-for="item in selectOptions"
      :key="item.value"
      :label="item.label"
      :value="item.value"
    />
    <VabElSelectLoading
      :page="page"
      :loading="loading"
      :hasMore="hasMore"
      @loadMore="handleLoadMore"
    />
  </el-select>
</template>

<script setup lang="ts">

/**
 * @import
 */
import _ from "lodash";
import { ref } from "vue";
import { getProductSearchSelect } from "~/src/api/dms/product";
import {getGroupOrderoption, getOrderOption, getRefundAfterOpton} from "/@/api/dms/refund";

/**
 * @props
 */
const props = defineProps({
  value: {
    type: String,
    default: ''
  },
  type: {
    type: String,
    default: '', // number, name, barcode
  },
  multiple: {
    type: Boolean,
    default: false
  },
  clearable: {
    type: Boolean,
    default: true
  },
  disabled: {
    type: Boolean,
    default: false
  }

})

/**
 * @var
 */

const proxy: any = getCurrentInstance()?.proxy

const page = ref(1);
const loading = ref(false);
const hasMore = ref(true);

const selectValue = ref<any>();
const sreachValue = ref<any>('')
const selectOptions = ref<any[]>([]);


const emit = defineEmits(['LazyChange'])

/**
 * 加载数据列表
 */
const loadDataList = async () => {
  try {
    loading.value = true;

    // 参数
    let data = {
      page: page.value,
      limit: 50,
      keyword:sreachValue.value,
    }

    // api

const res:any =  await  getApiList(data)
    // 遍历获取
    const list = res.data.lists.map((item: any) => {
      return { value: item, label: item }
    }) || []

    if (page.value == 1) selectOptions.value = [];

    selectOptions.value.push(...list);

    hasMore.value = selectOptions.value.length < res.data.count
  } catch (err) {
    console.error(err);
  } finally {
    loading.value = false;
  }
};

/**
 * 加载更多数据
 */
const handleLoadMore = async (value:any) => {
  page.value = value
  loadDataList();
};

/**
 * 模糊搜索
 */
const handleQuerySearch = _.throttle((value: any) => {
  // 去空格 大小写
  sreachValue.value = value?.trim().toLowerCase().replace(/\s+/g, '\n')
  page.value = 1
  // 加载数据
  loadDataList()
}, 500)
const getApiList = async (data:any)=>{
  let arr:any = []
  if(props.type == '1'){
    arr =   await getGroupOrderoption({ ...data })
  }else if(props.type == '2'){
    arr =   await getOrderOption({ ...data })
  }else if(props.type == '3'){
    arr =   await getRefundAfterOpton({ ...data })
  }
  return arr
}
/**
 * change
 */
const handleQueryChange = (value: any) => {
  emit('LazyChange', value)
}
const visibleList = (va:any)=>{
  if (va){
    loadDataList()
  }
}
</script>

<style lang="scss" scoped></style>
